/**
 * 
 */
package com.fbty.mt.action.user;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;

import javax.servlet.http.Cookie;

import com.fbty.base.action.BaseAction;
import com.fbty.mt.domain.User;
import com.fbty.mt.domain.UserTemp;
import com.fbty.mt.service.LoginService;
import com.fbty.mt.service.UserIpInfoService;
import com.fbty.mt.service.UserService;
import com.fbty.mt.utils.DegistUtil;
import com.fbty.mt.utils.EmailUtil;
import com.fbty.mt.utils.ImgCode;

/**
 * 
 * @author Administrator
 *
 */
public class LoginAction extends BaseAction {

	private User user;
	private UserService userService;
	private LoginService loginService;
	private UserIpInfoService userIpInfoService;
	private static final long serialVersionUID = 1L;
	private boolean flag;
	private String validateName;
	
	private String username;
	
	private String password;
	private Integer state = 0;
	private String verifycode;
	
	private String message = "";
	private Integer id;
	private Long validTime;
	/**
	 * 用户名和密码验证
	 * @return
	 * @throws Exception
	 */
	public String login() throws Exception {
		/*User u = (User)sessionMap.get("user");
		String name = u.getName();
		//String roleId = userService.findUserRole(u.getId());
		Integer num = getNum(u.getId());
		sessionMap.put("num", num);
		sessionMap.put("roleId", u.getMember());
		switch (u.getMember()) {
		case 1:
			sessionMap.put("info", " 管理员 ");
			return "admin";
		case 2:
			sessionMap.put("info", "<span style='color:green'>"+name+"</span> | 普通会员 | 您目前还剩下<span style='color:red'>"+num+"</span>条购买数量 | ");
			break;
		case 3:
			sessionMap.put("info", "<span style='color:green'>"+name+"</span> | 包月会员 | 您目前还剩下"+num+"条!| ");
			break;
		case 4:
			sessionMap.put("info", "<span style='color:green'>"+name+"</span> | 独享用户 | 您目前还剩下"+num+"条! | ");
			break;
		}
		return SUCCESS;*/
		
		
		String code = (String)sessionMap.get("code");
		if(code.equals(verifycode.toUpperCase())){
			User u = userService.findByUsername(username);
			if(u==null){
				message = "帐号错误或密码错误!";
			}else{
				if(u.getType()==3) {
					message = username+" 已被锁定,请用注册邮件找回密码!";
				} else if(u.getPassword().equals(DegistUtil.md5Digest(password))){
					sessionMap.put("user", u);
					int num = userService.updateMonthNum(u.getId());
					userIpInfoService.modifyEndTimeIp();
					sessionMap.put("monthNum",num);
					sessionMap.put("num",u.getNum());
				} else {
					u.setType(u.getType()+1);
					userService.updateUser(u);
					message = "该帐号错误登陆"+u.getType()+"次";
				}
			}
		} else {
			message = "验证码错误!";
		}
		sessionMap.put("loginMsg", message);
		return "success";
		
	}

	public String goToMain() throws Exception {
		User u = (User) sessionMap.get("user");
		if(u==null){
			return "error";
		}
		if(u.getState()==2){
			Boolean adminLoginFlag = (Boolean) sessionMap.get("adminLoginFlag");
			if(adminLoginFlag!=null) {
				if("admin".equals(u.getUsername())) {
					return "superAdminLogin";
				} else {
					return "adminLogin";
				}
			}
			String adminCode = ImgCode.getCode();
			System.out.println(adminCode);
			if(EmailUtil.sendEmailCode("代理天下-管理员登验证码!",adminCode,u.getEmail())) {
				sessionMap.put("adminCode", adminCode);
				userIpInfoService.modifyEndTimeIp();
				return "admin";
			} else {
				requestMap.put("wrongpwd", "系统内部错误!");
				return "login";
			}
		}else{
			return "success";
		}
	}
	public String adminLogin() throws Exception {
		User u = (User) sessionMap.get("user");
		if(u==null){
			message = "<span style='color:red'>帐号不存在</span>";
			return "login";
		}
		String code = (String)sessionMap.get("adminCode");
		if(verifycode.equalsIgnoreCase(code)) {
			sessionMap.put("adminLoginFlag", true);
			if("admin".equals(u.getUsername())) {
				return "superAdminLogin";
			} else {
				return "adminLogin";
			}
		} else {
			message = "<span style='color:red'>验证码不正确</span>";
			return "admin";
		}
		
	}
	/**
	 * 通过userId找到该用户还有多少条可用条数
	 * 根据tab_recharge这张表的date字段和当前时间进行比较，如果大于30天，说明该记录拥有的条数就失效
	 * 最后要更新user类里面的num
	 * @return
	 */
	public Integer  getNum(Integer uid) throws Exception {
		return userService.getNum(uid);
	}
	/**
	 * 注册用户
	 * @return
	 * @throws Exception
	 */
	public String regist() throws Exception {
		if(id == null && validTime == null) {
			return "error";
		}
		Integer pid = id/250-165974;
		UserTemp userTemp = userService.getUserTempById(pid);
		
		if(userTemp==null || userTemp.getValidTime() != (validTime-4894)) {//如果传过来的时间不等于临时表里面的时间.报错
			return "error";
		}
		/**
		 * 验证用户邮箱或帐号是否存在
		 */
		Boolean vFlag = userService.validUserName(userTemp);
		if(vFlag) {
			return "error";
		}
		User u = new User();
		u.setEmail(userTemp.getEmail());
		u.setPassword(DegistUtil.md5Digest(userTemp.getPassword()));
		u.setQq(userTemp.getQq());
		u.setUsername(userTemp.getUsername());
		u.setType(0);
		int id = userService.saveUser(u);
		u.setId(id);
		userIpInfoService.modifyEndTimeIp();
		sessionMap.put("user", u);
		sessionMap.put("monthNum",0);
		sessionMap.put("num",0);
		
		/**
		 * 注册完成后,删除注册临时表的内容
		 */
		state = 3;
		userService.deleteUserTemp(userTemp);
		return SUCCESS;
	}
	public String emailValid() throws Exception {
		if(user == null) {
			return ERROR;
		}
		flag = userService.validEmail(user.getEmail());
		if(!flag) {
			message = "该邮箱已被注册，请换一个邮箱!";
			return "email";
		}
		Long time = new Date().getTime();
		//第一步,将用户信息表存到UserTemp中
		UserTemp userTemp = new UserTemp();
		userTemp.setEmail(user.getEmail());
		userTemp.setPassword(user.getPassword());
		userTemp.setQq(user.getQq());
		userTemp.setUsername(user.getUsername());
		userTemp.setState(0);
		userTemp.setValidTime(time);
		Integer tempId = userService.saveUserTemp(userTemp);
		//发送给邮箱，这个时间用来匹配是否是同一条记录，匹配时要减1111
//		String ip = getIp(time);
		String path = "http://127.0.0.1:8080/mt/";//本机测试
//		String path = "http://121.14.220.108/"; //用在正式布署
//		String msg = "<a href='http://"+ip+":8080/mt/user/user!regist.do?validTime="+time+"'>请击此处完成注册</a>";
		String msg = "尊敬的：代理天下用户<br />您好<br />您的代理天下帐户信息为:"+userTemp.getUsername()+
				"<br />"+path+"user/user!regist.do?id="+(tempId+165974)*250+"&validTime="+(time+4894) +
				"<br />请点击该连接或复制地址到地址完成注册";
		
		
		EmailUtil.sendEmail("代理天下-账户激活!",msg,userTemp.getEmail());
		state = 2;
		return "emailValid";
	}
	public String check(){
		flag = loginService.validLogin(validateName);
		return "ok";
		
	}
	
	public String checkEmail(){
		flag = userService.validEmail(user.getEmail());
		return "ok";
		
	}
	
	
	
	public String logout(){
		sessionMap.clear();
		request.getSession().invalidate();
		return "logout";
	}
	
	public UserService getUserService() {
		return userService;
	}


	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public void setValidateName(String validateName) {
		this.validateName = validateName;
	}
	public boolean isFlag() {
		return flag;
	}
	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getVerifycode() {
		return verifycode;
	}
	public void setVerifycode(String verifycode) {
		this.verifycode = verifycode;
	}
	
	
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String load(){
		user = (User)sessionMap.get("user");
		return "load";
		
	}
	
	public String update(){
		User u = userService.findUserById(id);
		u.setPassword(DegistUtil.md5Digest(password));
		u.setQq(user.getQq());
		u.setEmail(user.getEmail());
		userService.updateUser(u);
		sessionMap.clear();
		request.getSession().invalidate();
		return "logout";
		
	}
	
	public String ynLogin(){
		User u = (User)sessionMap.get("user");
		if(u!=null){
			flag=true;
		}
		return "ynLogin";
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	public void setUserIpInfoService(UserIpInfoService userIpInfoService) {
		this.userIpInfoService = userIpInfoService;
	}
	
	public static String getIp(Long time) {
		 InputStream in = null;
	        OutputStream out = null;
	        try {
	            // 检查命令行参数
	            if (false)
	                throw new IllegalArgumentException("Wrong number of args");
	            // URL url = new URL("http://www.ip138.com/ip2city.asp"); //创建 URL
	            // 得到一个输入流
	            // URL url = new URL("http://202.105.81.135/showip/"); //创建 URL
//	             URL url = new URL("http://www.ip.cn/"); //创建 URL
	            URL url = new URL("http://www.118114ok.com/resin-admin/"); // 创建 URL
	            in = url.openStream(); // 打开到这个URL的流
	                out = System.out;
	            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
	            String inputLine = "";
	            String ip="";
	            while ((inputLine = reader.readLine()) != null){
	            	Integer start = inputLine.indexOf(">")+1;
	            	ip = inputLine.substring(start).trim();
	            	ip = ip.substring(0,ip.indexOf("<"));
	             }
	            return ip;
	        }catch (Exception e) {
	            System.err.println(e);
	            System.err.println("Usage: java GetURL <URL> [<filename>]");
	        } finally { // 无论如何都要关闭流
	            try {
	                in.close();
	                out.close();
	            } catch (Exception e) {
	            }
	        }
			return "";
	}

	public Long getValidTime() {
		return validTime;
	}

	public void setValidTime(Long validTime) {
		this.validTime = validTime;
	}

	public Integer getState() {
		return state;
	}

	public void setState(Integer state) {
		this.state = state;
	}
	
}
